package com.fanfan.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fanfan.dao.MenuDao;
import com.fanfan.pojo.Menu;
import com.fanfan.pojo.Role;
import com.fanfan.pojo.RoleMenu;
import com.fanfan.pojo.domain.ResponseResult;
import com.fanfan.pojo.vo.CheckedKeysVo;
import com.fanfan.pojo.vo.MenuDto;
import com.fanfan.pojo.vo.MenuVo;
import com.fanfan.service.MenuService;
import com.fanfan.service.RoleMenuService;
import com.fanfan.utils.BeanCopyUtils;
import com.fanfan.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限表(Menu)表服务实现类
 *
 * @author fansea
 * @since 2023-02-24 14:03:19
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {
    @Autowired
    RoleMenuService roleMenuService;

    @Override
    public List<String> selectPermsByUserId(Long id) {
        //定义id=1L时为超级管理员，拥有所有权限
        if (id==1L){
            LambdaQueryWrapper<Menu> wrapper=new LambdaQueryWrapper<>();
            wrapper.in(Menu::getMenuType,"C","F");
            List<Menu> list = list(wrapper);
            List<String> perms = list.stream().map(Menu::getPerms).collect(Collectors.toList());
            return perms;
        }
        return  getBaseMapper().selectPermsByUserId(id);
    }

    @Override
    public List<Menu> selectRouterMenuTreeByUserId(Long userId) {
        MenuDao menuDao=getBaseMapper();
        List<Menu> menus=null;
        /*1.user_role查询角色信息id
          2.role_menu查询角色对应的menuId
          以上操作直接定义Mapper文件自写sql完成*/
        if (SecurityUtils.isAdmin()){
            menus=menuDao.selectAllRouterMenu();
        }else {
            menus=menuDao.selectRouterMenuTreeByUserId(userId);
        }
        //这里的menus是根据userID，menuType查询到的符合条件的目录
        //0L代表查询根目录
        List<Menu> menuTree = builderMenuTree(menus,0L);
        return menuTree;
        //封装routersVo
    }

    @Override
    public ResponseResult listMenu(MenuVo menuVo) {
        LambdaQueryWrapper<Menu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(menuVo.getMenuName()),Menu::getMenuName,menuVo.getMenuName());
        queryWrapper.eq(StringUtils.hasText(menuVo.getStatus()),Menu::getStatus,menuVo.getStatus());
        queryWrapper.orderByAsc(Menu::getOrderNum);
        List<Menu> menuList = getBaseMapper().selectList(queryWrapper);
        return ResponseResult.okResult(menuList);
    }

    @Override
    public List<MenuDto> treeSelectMenu() {
        LambdaQueryWrapper<Menu> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(Menu::getParentId,0);
        List<Menu> rootList = getBaseMapper().selectList(queryWrapper);
        List<MenuDto> copyAllList = BeanCopyUtils.copyList(getBaseMapper().selectList(null), MenuDto.class);
        List<MenuDto> menuDtos = BeanCopyUtils.copyList(rootList, MenuDto.class);
        List<MenuDto> menuDtoList = menuDtos.stream()
                .map(menuDto -> menuDto.setLabel(getLabel(menuDto.getId())))
                .map(menuDto -> menuDto.setChildren(getChildren(menuDto,copyAllList)))
                .collect(Collectors.toList());
        return menuDtoList;
    }

    @Override
    public ResponseResult roleMenuTreeSelect(Long id) {
        LambdaQueryWrapper<RoleMenu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId,id);
        List<Long> checkedKeys = roleMenuService.getBaseMapper().selectList(queryWrapper).stream()
                .map(m -> m.getMenuId())
                .collect(Collectors.toList());
        return ResponseResult.okResult(new CheckedKeysVo(treeSelectMenu(),checkedKeys));

    }

    private List<Menu> builderMenuTree(List<Menu> menus, long perm) {
        List<Menu> menuTree = menus.stream()
                .filter(menu -> menu.getParentId().equals(perm))
                .map(menu -> menu.setChildren(getChildren(menu, menus)))
                .collect(Collectors.toList());
        return menuTree;

    }
    //menu表示要查的根目录0L，menus表示需要从符合条件的目录集合查询
    private List<Menu> getChildren(Menu menu, List<Menu> menus) {
        List<Menu> childrenList = menus.stream()
                .filter(m -> m.getParentId().equals(menu.getId()))
                .map(m -> m.setChildren(getChildren(m, menus)))
                .collect(Collectors.toList());
        return childrenList;
    }
    private List<MenuDto> getChildren(MenuDto menuDto, List<MenuDto> menus) {
        List<MenuDto> childrenList = menus.stream()
                .filter(m -> m.getParentId().equals(menuDto.getId()))
                .map(m -> m.setLabel(getLabel(m.getId())))
                .map(m -> m.setChildren(getChildren(m, menus)))
                .collect(Collectors.toList());
        return childrenList;
    }
    private String getLabel(Long id){
        return getBaseMapper().selectById(id).getMenuName();
    }
}








